package signHelper.dao;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import signHelper.modle.CourseRecord;

@Repository
public class CourseRecordDao {
	private final Logger logger = LogManager.getLogger(getClass());
	private static final RowMapper<CourseRecord> rm = JdbcHelper.getRowMapper(CourseRecord.class);
	private @Autowired JdbcTemplate jdbcTemplate;
	private @Autowired NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public CourseRecord add(CourseRecord param) {
		param.setId(JdbcHelper.insertAndGetKey(namedParameterJdbcTemplate, Sql.ADD, param));
		return param;
	}

	public CourseRecord getById(Integer id) {
		return JdbcHelper.queryForObject(jdbcTemplate, Sql.GET_BY_ID, rm, id);
	}

	public List<CourseRecord> query(CourseRecord param, Integer has, Integer nextSize) {
		StringBuffer sql = new StringBuffer(Sql.GET);
		if (param.getCourseId()!=null) {
			sql.append(" and course_id=:courseId");
		}
		if (has != null && nextSize != null)
			sql.append(" limit ").append(has).append(",").append(nextSize);
		return namedParameterJdbcTemplate.query(sql.toString(), JdbcHelper.getSqlParameterSource(param), rm);
	}

	public void update(CourseRecord bean) {
		namedParameterJdbcTemplate.update(Sql.UPDATE, JdbcHelper.getSqlParameterSource(bean));
	}

	public void delete(Integer id) {
		jdbcTemplate.update(Sql.DEL_BY_ID, id);
	}

	private class Sql {
		public static final String GET = "select * from course_record where 1=1";
		public static final String GET_BY_ID = "select * from course_record where id=?";
		public static final String ADD = "insert into course_record (course_id,start_time,end_time,create_date,update_date) values (:courseId,:startTime,:endTime,now(),now())";
		public static final String DEL_BY_ID = "delete from course_record where id=?";
		public static final String UPDATE = "update course_record set course_id=ifnull(:courseId,course_id),start_time=ifnull(:startTime,start_time), end_time=ifnull(:endTime,end_time) where id=:id";
	}
	
}
